package com.xyx.spring.ServiceImpl;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.xyx.spring.Dao.FileDao;
import com.xyx.spring.Model.Files;
import com.xyx.spring.Model.User;
import com.xyx.spring.Service.FileService;
import com.xyx.spring.Utils.DataWrapper;
import com.xyx.spring.Utils.MD5Util;
import com.xyx.spring.Utils.PdfFileToImage;
import com.xyx.spring.Utils.SessionManager;

@Service("fileService")
public class FileServiceImpl implements FileService  {
	@Autowired
	FileDao fileDao;
	@Override
	public DataWrapper<List<String>> uploadFile(String filePath, MultipartFile[] file, Integer fileType,HttpServletRequest request,String token,Integer exchange) {
		DataWrapper<List<String>> test = new DataWrapper<List<String>>();
		List<String> urls = new ArrayList<String>();
		//User user = SessionManager.getSession(token);
		
		if (file == null || filePath == null || filePath.equals("")) {
			return null;
		}
		for(int i=0;i<file.length;i++){
			String rootPath = request.getSession().getServletContext().getRealPath("/");
	        String newFileName = MD5Util.getMD5String(file[i].getOriginalFilename() + new Date() + UUID.randomUUID().toString()).replace(".","")
	                    + file[i].getOriginalFilename().substring(file[i].getOriginalFilename().lastIndexOf("."));
	        //批量导入。参数：文件名，文件。
//		        boolean b = itemService.batchImport(newFileName,file);
	        File fileDir = new File(rootPath + "/" + filePath);
	        Files files=new Files();
	        if (!fileDir.exists()) {
	            fileDir.mkdirs();
	        }
	        String realPath="";
	        try { 
	            FileOutputStream out = new FileOutputStream(rootPath + "/" + filePath + "/"
	                    + newFileName);
	            BufferedOutputStream bos=new BufferedOutputStream(out);
	                // 写入文件
	            bos.write(file[i].getBytes());
	            bos.flush();
	            bos.close();
	            Date date=new Date();
	            DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	            String time=format.format(date);
	            files.setDesc(time);
	            realPath=filePath + "/"+ newFileName;
	            files.setName(newFileName);//////构件的url
	            files.setUrl(realPath);
	            files.setFileType(fileType);
	            files.setRealName(file[i].getOriginalFilename().substring(0,file[i].getOriginalFilename().lastIndexOf(".")));
	            fileDao.addFiles(files);
	            

	        } catch (Exception e) {
	            e.printStackTrace();
	            return null;
	        }
	        if(exchange!=null && exchange==1){
	        	PdfFileToImage pdfUtil = new PdfFileToImage();
				File pdfFile =new File(rootPath + "/" + filePath + "/"+ newFileName);
				//上传的是png格式的图片结尾
				String path = filePath + "/"+UUID.randomUUID().toString()+".png";
				String targetfile=rootPath + "/" + path;
				if(pdfUtil.pdfFileToImage(pdfFile,targetfile)){
					urls.add(path);
				}
			}else{
				 urls.add(realPath);
			}
		}
		test.setData(urls);
        return test;
	}

	@Override
	public boolean deleteFileByPath(String filePathAndName,HttpServletRequest request) {
		// TODO Auto-generated method stub
		boolean flag = false;
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		File file = new File(rootPath + filePathAndName);
        try {
            flag = file.delete();
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return flag;
	}

	@Override
	public Files getById(Long id) {
		// TODO Auto-generated method stub
		return fileDao.getById(id);
	}

	@Override
	public boolean deleteFileById(Long id) {
		// TODO Auto-generated method stub
		return fileDao.deleteFiles(id);
	}

	@Override
	public boolean addFile(Files file) {
		// TODO Auto-generated method stub
		return fileDao.addFiles(file);
	}

	@Override
	public DataWrapper<List<Files>> getAllFiles(String token,String fileName) {
		// TODO Auto-generated method stub
		DataWrapper<List<Files>> result = new DataWrapper<List<Files>>();
		User user = SessionManager.getSession(token);
		if(user!=null){
			List<Files> datas = new ArrayList<Files>();
			datas = fileDao.getFilesList(fileName);
			result.setData(datas);
		}
		return result;
	}

	@Override
	public Files uploadFiles(String filePath, MultipartFile file, Integer fileType, HttpServletRequest request) {
		if (file == null || filePath == null || filePath.equals("")) {
			return null;
		}
		String rootPath = request.getSession().getServletContext().getRealPath("/");
        String newFileName = MD5Util.getMD5String(file.getOriginalFilename() + new Date() + UUID.randomUUID().toString()).replace(".","")
                    + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //批量导入。参数：文件名，文件。
//        boolean b = itemService.batchImport(newFileName,file);
        File fileDir = new File(rootPath + "/" + filePath);
        Files files=new Files();
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String realPath="";
        try {
            FileOutputStream out = new FileOutputStream(rootPath + "/" + filePath + "/"
                    + newFileName);
                // 写入文件
            out.write(file.getBytes());
            out.flush();
            out.close();
           
            
            Date date=new Date();
            DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time=format.format(date);
            files.setDesc(time);
            realPath=filePath + "/"+ newFileName;
            files.setName(newFileName);//////构件的url
            files.setUrl(realPath);
            files.setFileType(fileType);
            files.setRealName(file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf(".")));
            fileDao.addFiles(files);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return files;
	}
	public static BufferedReader readTxt(File file) {
		  try {
		    if(file.isFile() && file.exists()) {
		      InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
		      BufferedReader br = new BufferedReader(isr);
		      String lineTxt = null;
		      while ((lineTxt = br.readLine()) != null) {
		        System.out.println(lineTxt);
		      }
		      br.close();
		      return br;
		    } else {
		      System.out.println("文件不存在!");
		    }
		  } catch (Exception e) {
		    System.out.println("文件读取错误!");
		  }
		  return null;
    }
	@Override
	public DataWrapper<String> changeFiles(MultipartFile newFile, Integer filetype,
			HttpServletRequest request, String token, String oldFileUrl) {
		DataWrapper<String> test = new DataWrapper<String>();
		User user = SessionManager.getSession(token);
		if(user!=null){
			if (newFile == null || oldFileUrl == null || oldFileUrl.equals("")) {
				return null;
			}
			String rootPath = request.getSession().getServletContext().getRealPath("/");
	        //批量导入。参数：文件名，文件。
//	        boolean b = itemService.batchImport(newFileName,file);
	        File fileDir = new File(rootPath + "/" + oldFileUrl);
	        if (!fileDir.exists()) {
	            test.setData("传参有问题");
	        }else{
	             if(newFile!=null && fileDir!=null){
	            	 test.setData(oldFileUrl);
	            	 try {
	            		 FileOutputStream out = new FileOutputStream(rootPath + oldFileUrl);
							out.write(newFile.getBytes());
			 	            out.flush();
			 	            out.close();
	                 } catch (Exception e) {
	                     e.printStackTrace();
	                     return null;
	                 }
	             }
	        }
		}
        return test;
	}

}
